import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'index.dart';
import '../../../common/utils/index.dart';
import '../../../common/routers/index.dart';

/// 我的页面视图
/// 
/// 显示用户个人信息和相关功能入口
/// 包含用户头像、基本信息、功能菜单和退出登录等
/// 遵循GetX视图标准化结构
class MyIndexPage extends GetView<MyIndexController> {
  const MyIndexPage({super.key});

  // 主视图构建方法
  Widget _buildView() {
    // 统一的错误和加载状态处理
    if (controller.hasError.value) {
      return _buildErrorView();
    }
    
    return Column(
      children: [
        // 固定的用户信息头部区域
        _buildUserHeader(),
        // 可滚动的内容区域
        Expanded(
          child: RefreshIndicator(
            onRefresh: controller.refreshUserInfo,
            child: SingleChildScrollView(
              physics: const AlwaysScrollableScrollPhysics(),
              child: Column(
                children: [
                  const SizedBox(height: 20),
                  // 用户详细信息
                  // _buildUserInfoSection(),
                  const SizedBox(height: 20),
                  // 功能菜单
                  _buildMenuSection(),
                  const SizedBox(height: 20),
                  // 退出登录按钮
                  _buildLogoutSection(),
                  const SizedBox(height: 40),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 构建错误状态视图
  Widget _buildErrorView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.error_outline,
            size: 64,
            color: Colors.red.shade400,
          ),
          const SizedBox(height: 16),
          Text(
            controller.errorMessage.value,
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey.shade600,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 24),
          ElevatedButton.icon(
            onPressed: controller.resetErrorState,
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue.shade600,
              foregroundColor: Colors.white,
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
            ),
            icon: const Icon(Icons.refresh),
            label: const Text('重试'),
          ),
        ],
      ),
    );
  }

  /// 构建用户头部信息
  Widget _buildUserHeader() {
    // 获取状态栏高度
    final statusBarHeight = MediaQuery.of(Get.context!).padding.top;
    // AppBar标准高度是56
    const appBarHeight = 56.0;
    
    return Container(
      width: double.infinity,
      // 动态计算顶部padding，为状态栏和AppBar留出空间，但减少底部padding因为下面有内容
      padding: EdgeInsets.only(
        top: statusBarHeight + appBarHeight + 10, // 状态栏 + AppBar + 少量间距
        bottom: 20, // 减少底部间距
        left: 20,
        right: 20,
      ),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Colors.blue.shade600,
            Colors.blue.shade800,
          ],
        ),
        borderRadius: const BorderRadius.only(
          bottomLeft: Radius.circular(30),
          bottomRight: Radius.circular(30),
        ),
        // 添加阴影效果，让固定头部与滚动内容区分开
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 10,
            spreadRadius: 0,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      child: Row(
        children: [
          // 左侧：用户头像
          _buildUserAvatar(),
          const SizedBox(width: 20),
          // 右侧：用户信息（名称和用户名）
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 用户名称（可点击）
                _buildUserName(),
                const SizedBox(height: 4),
                // 用户名
                _buildUserNameDisplay(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建用户头像
  Widget _buildUserAvatar() {
    return GestureDetector(
      onTap: controller.onAvatarTap,
      child: Hero(
        tag: 'user_avatar',
        child: Container(
          width: 80,
          height: 80,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(12), // 正方形圆角
            border: Border.all(
              color: Colors.white,
              width: 3,
            ),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.2),
                blurRadius: 10,
                spreadRadius: 2,
              ),
            ],
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(9), // 内容圆角比容器小一点
            child: controller.userAvatarUrl.isNotEmpty
                ? Image.network(
                    controller.userAvatarUrl,
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) => _buildDefaultAvatar(),
                  )
                : _buildDefaultAvatar(),
          ),
        ),
      ),
    );
  }

  /// 构建默认头像
  Widget _buildDefaultAvatar() {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(9),
        gradient: RadialGradient(
          colors: [
            Colors.grey.shade300,
            Colors.grey.shade500,
          ],
        ),
      ),
      child: const Icon(
        Icons.person,
        size: 40,
        color: Colors.white,
      ),
    );
  }

  /// 构建用户名称（可点击编辑）
  Widget _buildUserName() {
    return GestureDetector(
      onTap: controller.onUserNameTap,
      child: Text(
        controller.userDisplayName,
        style: const TextStyle(
          fontSize: 24,
          fontWeight: FontWeight.bold,
          color: Colors.white,
        ),
      ),
    );
  }

  /// 构建用户名显示
  Widget _buildUserNameDisplay() {
    return Text(
      '@${controller.userName}',
      style: TextStyle(
        fontSize: 14,
        color: Colors.white.withOpacity(0.8),
      ),
    );
  }

  /// 构建功能菜单区域
  Widget _buildMenuSection() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 10,
            spreadRadius: 2,
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '功能菜单',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: Colors.black87,
            ),
          ),
          const SizedBox(height: 16),
          // 动态构建菜单项
          ...controller.settingsMenu.asMap().entries.map((entry) {
            final index = entry.key;
            final menuItem = entry.value;
            final isLast = index == controller.settingsMenu.length - 1;
            
            return _buildMenuItem(
              icon: menuItem.icon,
              title: menuItem.title,
              subtitle: menuItem.subtitle,
              onTap: () => _handleMenuTap(menuItem.title),
              isLast: isLast,
            );
          }).toList(),
        ],
      ),
    );
  }
  
  /// 处理菜单项点击
  void _handleMenuTap(String title) {
    switch (title) {
      case '设置':
        controller.onSettingsTap();
        break;
      case '关于我们':
        controller.onAboutTap();
        break;
      default:
        break;
    }
  }

  /// 构建菜单项
  Widget _buildMenuItem({
    required IconData icon,
    required String title,
    required String subtitle,
    required VoidCallback onTap,
    bool isLast = false,
  }) {
    return Column(
      children: [
        InkWell(
          onTap: onTap,
          borderRadius: BorderRadius.circular(8),
          child: Container(
            padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 8),
            child: Row(
              children: [
                Container(
                  width: 40,
                  height: 40,
                  decoration: BoxDecoration(
                    color: Colors.blue.shade50,
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: Icon(
                    icon,
                    size: 20,
                    color: Colors.blue.shade600,
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        title,
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                          color: Colors.black87,
                        ),
                      ),
                      Text(
                        subtitle,
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey.shade600,
                        ),
                      ),
                    ],
                  ),
                ),
                Icon(
                  Icons.arrow_forward_ios,
                  size: 16,
                  color: Colors.grey.shade400,
                ),
              ],
            ),
          ),
        ),
        if (!isLast) ...[
          const SizedBox(height: 8),
          Divider(
            height: 1,
            color: Colors.grey.shade200,
            indent: 52,
          ),
          const SizedBox(height: 8),
        ],
      ],
    );
  }

  /// 构建退出登录区域
  Widget _buildLogoutSection() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      child: SizedBox(
        width: double.infinity,
        height: 50,
        child: ElevatedButton.icon(
          onPressed: controller.isLoading.value ? null : controller.onLogoutTap,
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.red.shade600,
            foregroundColor: Colors.white,
            elevation: 2,
            shadowColor: Colors.red.withOpacity(0.3),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
          ),
          icon: controller.isLoading.value
              ? const SizedBox(
                  width: 20,
                  height: 20,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                  ),
                )
              : const Icon(Icons.logout),
          label: Text(
            controller.isLoading.value ? '退出中...' : '退出登录',
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 设置我的页面状态栏样式 - 深色背景使用浅色图标
    SystemUIUtils.setTransparentStatusBarLight();
    
    return GetBuilder<MyIndexController>(
      init: MyIndexController(),
      id: "my_index",
      builder: (_) {
        return Scaffold(
          backgroundColor: Colors.grey.shade50,
          extendBodyBehindAppBar: true, // 让body延伸到AppBar下方
          appBar: _buildAppBar(),
          body: _buildView(), // 移除SafeArea，让内容可以延伸到AppBar下方
        );
      },
    );
  }
  
  /// 构建应用栏
  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      // title: Text(controller.pageTitle),
      backgroundColor: Colors.transparent, // 设置为透明
      foregroundColor: Colors.white,
      elevation: 0, // 移除阴影
      centerTitle: true,
      // 左侧：测试按钮（仅在调试模式下显示）
      leading: kDebugMode
          ? IconButton(
              onPressed: () {
                // 跳转到测试页面
                Get.toNamed(RouteNames.testTestIndex);
              },
              icon: const Icon(
                Icons.bug_report_outlined,
                color: Colors.white,
              ),
              tooltip: '测试页面',
            )
          : null,
      actions: [
        // 设置按钮
        IconButton(
          onPressed: controller.onSettingsTap,
          icon: const Icon(
            Icons.settings_outlined,
            color: Colors.white,
          ),
          tooltip: '设置',
        ),
        // 刷新状态指示器
        if (controller.isRefreshing.value)
          const Padding(
            padding: EdgeInsets.only(right: 16.0),
            child: Center(
              child: SizedBox(
                width: 20,
                height: 20,
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                ),
              ),
            ),
          ),
        // 错误状态指示器
        if (controller.hasError.value)
          Padding(
            padding: const EdgeInsets.only(right: 16.0),
            child: IconButton(
              onPressed: controller.resetErrorState,
              icon: const Icon(
                Icons.error_outline,
                color: Colors.red,
              ),
              tooltip: '重置错误状态',
            ),
          ),
      ],
    );
  }
}
